package com.sky.controller.user;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.sky.constant.UserActionConstant;
import com.sky.context.BaseContext;
import com.sky.result.Result;
import com.sky.service.RecommendationService;
import com.sky.service.UserBorrowService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 用户借阅相关接口
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserBorrowController {

    @Autowired
    private UserBorrowService userBorrowService;

    @Autowired
    private RecommendationService recommendationService;

    /**
     * 申请借阅图书
     * @param bookId 图书ID
     * @return 操作结果
     */
    @SaCheckLogin
    @PostMapping("/borrow/request/{bookId}")
    public Result requestBorrow(@PathVariable Integer bookId) {
        log.info("申请借阅图书：{}", bookId);
        try {
            Integer userId = Math.toIntExact(BaseContext.getCurrentId());
            userBorrowService.submitBorrowRequest(userId, bookId);
            recommendationService.recordUserAction(userId, bookId, UserActionConstant.BORROW);
            return Result.success();
        } catch (Exception e) {
            log.error("申请借阅失败", e);
            return Result.error("申请借阅失败：" + e.getMessage());
        }
    }

    /**
     * 取消借阅申请
     * @param requestId 申请ID
     * @return 操作结果
     */
    @SaCheckLogin
    @DeleteMapping("/borrow/cancel/{requestId}")
    public Result cancelBorrowRequest(@PathVariable String requestId) {
        log.info("取消借阅申请：{}", requestId);
        try {
            // 1. 获取当前用户ID
            Integer userId = Math.toIntExact(BaseContext.getCurrentId());

            // 2. 取消借阅申请
            userBorrowService.cancelBorrowRequest(userId, requestId);

            return Result.success();
        } catch (Exception e) {
            log.error("取消借阅申请失败", e);
            return Result.error("取消借阅申请失败：" + e.getMessage());
        }
    }

} 